package logic

import (
	"context"
	"crypto/md5"
	"fmt"
	"time"

	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type AuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthLogic {
	return &AuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AuthLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// MD5加密密码
	hasher := md5.New()
	hasher.Write([]byte(req.Password))
	hashedPassword := fmt.Sprintf("%x", hasher.Sum(nil))

	// 查找用户
	user, err := l.svcCtx.UserModel.FindByUsername(req.Username)
	if err != nil {
		return nil, fmt.Errorf("用户名或密码错误")
	}

	// 验证密码
	if user.Password != hashedPassword {
		return nil, fmt.Errorf("用户名或密码错误")
	}

	// 生成JWT token
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"iat":    now,
		"exp":    now + accessExpire,
		"userId": user.Id,
		"role":   user.Role,
	})

	accessToken, err := jwtToken.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
	if err != nil {
		return nil, err
	}

	return &types.LoginResp{
		Token: accessToken,
		UserInfo: types.User{
			Id:       user.Id,
			Username: user.Username,
			Name:     user.Name,
			Role:     user.Role,
			Phone:    user.Phone,
		},
	}, nil
}